/*****************************************************************************
*        描述 :
*             文件描述
*        CLR版本:            3.5
*        创建者 :            蒋 光
*        个人域名:           jiangguang.net.cn
*        命名空间名称:       ECP.DataAccess
*        文件名:             BaseFileDao.cs
*        创建系统时间:       2012/11/2 19:06:59
*        创建年份:           2012
*
/*****************************************************************************/

namespace ECP.DataAccess
{
    using System;
    using System.Data;
    using ECP.DataAccess.Utilities;
    using ECP.Model;
    using ECP.Utilities;

    public class BaseFileDao : BaseDao
    {
        public BaseFileDao()
        {
            base.CurrentTableName = BaseFileTable.TableName;
        }

        public BaseFileDao(IDbHelper dbHelper)
            : this()
        {
            base.DbHelper = dbHelper;
        }

        public BaseFileDao(BaseUserInfo userInfo)
            : this()
        {
            base.UserInfo = userInfo;
        }

        public BaseFileDao(IDbHelper dbHelper, BaseUserInfo userInfo)
            : this(dbHelper)
        {
            base.UserInfo = userInfo;
        }

        public string Add(string folderID, string fileName, string file, string description, string category, bool enabled, out string statusCode)
        {
            return this.Add(folderID, fileName, file, null, description, category, enabled, out statusCode);
        }

        public string Add(string folderID, string fileName, byte[] file, string description, string category, bool enabled, out string statusCode)
        {
            return this.Add(folderID, fileName, null, file, description, category, enabled, out statusCode);
        }

        private string Add(string folderID, string fileName, string file, byte[] byteFile, string description, string category, bool enabled, out string statusCode)
        {
            statusCode = string.Empty;
            BaseFileEntity fileEntity = new BaseFileEntity
            {
                FolderID = folderID,
                FileName = fileName,
                FileContent = byteFile,
                Description = description,
                Category = category,
                Enabled = enabled
            };
            string str = string.Empty;
            if (this.Exists(BaseFileTable.FieldFolderID, fileEntity.FolderID, BaseFileTable.FieldFileName, fileEntity.FileName))
            {
                statusCode = StatusCode.ErrorFullNameExist.ToString();
                return str;
            }
            str = this.AddEntity(fileEntity);
            statusCode = StatusCode.OKAdd.ToString();
            return str;
        }

        public string AddEntity(BaseFileEntity fileEntity)
        {
            string sequence = BaseSequenceDao.Instance.GetSequence(base.DbHelper, BaseFileTable.TableName);
            SQLBuilder builder = new SQLBuilder(base.DbHelper);
            builder.BeginInsert(BaseFileTable.TableName);
            builder.SetValue(BaseFileTable.FieldID, sequence);
            builder.SetValue(BaseFileTable.FieldFolderID, fileEntity.FolderID);
            builder.SetValue(BaseFileTable.FieldFileName, fileEntity.FileName);
            if (fileEntity.FileContent != null)
            {
                builder.SetValue(BaseFileTable.FieldFileSize, fileEntity.FileContent.Length);
            }
            builder.SetValue(BaseFileTable.FieldFilePath, fileEntity.FilePath);
            builder.SetValue(BaseFileTable.FieldCategory, fileEntity.Category);
            builder.SetValue(BaseFileTable.FieldDescription, fileEntity.Description);
            builder.SetValue(BaseFileTable.FieldEnabled, fileEntity.Enabled ? 1 : 0);
            builder.SetValue(BaseFileTable.FieldSortCode, sequence);
            builder.SetValue(BaseFileTable.FieldCreateUserID, base.UserInfo.ID);
            builder.SetValue(BaseFileTable.FieldCreateUserRealname, base.UserInfo.Realname);
            builder.SetDBNow(BaseFileTable.FieldCreateDate);
            builder.SetValue(BaseFileTable.FieldModifyUserID, base.UserInfo.ID);
            builder.SetValue(BaseFileTable.FieldModifyUserRealname, base.UserInfo.Realname);
            builder.SetDBNow(BaseFileTable.FieldModifyDate);
            builder.EndInsert();
            builder.BeginUpdate(BaseFileTable.TableName);
            if (fileEntity.FileContent != null)
            {
                builder.SetValue(BaseFileTable.FieldFileContent, fileEntity.FileContent);
            }
            builder.SetWhere(BaseFileTable.FieldID, sequence);
            if (builder.EndUpdate() <= 0)
            {
                return string.Empty;
            }
            return sequence;
        }

        public override int BatchSave(DataTable dataTable)
        {
            int num = 0;
            BaseFileEntity fileEntity = new BaseFileEntity();
            foreach (DataRow row in dataTable.Rows)
            {
                if (row.RowState == DataRowState.Deleted)
                {
                    string id = row[BaseFileTable.FieldID, DataRowVersion.Original].ToString();
                    if (id.Length > 0)
                    {
                        num += this.Delete(id);
                    }
                }
                if ((row.RowState == DataRowState.Modified) && (row[BaseFileTable.FieldID, DataRowVersion.Original].ToString().Length > 0))
                {
                    fileEntity.GetFrom(row);
                    num += this.UpdateEntity(fileEntity);
                }
                if (row.RowState == DataRowState.Added)
                {
                    fileEntity.GetFrom(row);
                    num += (this.AddEntity(fileEntity).Length > 0) ? 1 : 0;
                }
                if (row.RowState != DataRowState.Unchanged)
                {
                    DataRowState rowState = row.RowState;
                }
            }
            return num;
        }

        public int DeleteByFolder(string folderID)
        {
            return this.Delete(BaseFileTable.FieldFolderID, folderID);
        }

        public byte[] Download(string id)
        {
            this.UpdateReadCount(id);
            byte[] buffer = null;
            string sqlQuery = " SELECT " + BaseFileTable.FieldFileContent + "   FROM " + BaseFileTable.TableName + "  WHERE " + BaseFileTable.FieldID + " = " + base.DbHelper.GetParameter(BaseFileTable.FieldID);
            IDataReader reader = null;
            try
            {
                reader = base.DbHelper.ExecuteReader(sqlQuery, base.DbHelper.MakeParameters(BaseFileTable.FieldID, id));
                if (reader.Read())
                {
                    buffer = (byte[])reader[BaseFileTable.FieldFileContent];
                }
            }
            catch (Exception exception)
            {
                BaseExceptionDao.LogException(base.DbHelper, base.UserInfo, exception);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return buffer;
        }

        public BaseFileEntity GetEntity(string id)
        {
            string sqlQuery = string.Empty;
            sqlQuery = " SELECT " + BaseFileTable.FieldID + "        ," + BaseFileTable.FieldFolderID + "        ," + BaseFileTable.FieldFileName + "        ," + BaseFileTable.FieldFilePath + "        ," + BaseFileTable.FieldFileSize + "        ," + BaseFileTable.FieldReadCount + "        ," + BaseFileTable.FieldCategory + "        ," + BaseFileTable.FieldDescription + "        ," + BaseFileTable.FieldEnabled + "        ," + BaseFileTable.FieldSortCode + "        ," + BaseFileTable.FieldCreateUserID + "        ," + BaseFileTable.FieldCreateUserRealname + "        ," + BaseFileTable.FieldCreateDate + "        ," + BaseFileTable.FieldModifyUserID + "        ," + BaseFileTable.FieldModifyUserRealname + "        ," + BaseFileTable.FieldModifyDate + "      ,(SELECT " + BaseFolderTable.FieldFolderName + " FROM " + BaseFolderTable.TableName + " WHERE " + BaseFolderTable.FieldID + " = " + BaseFileTable.FieldFolderID + ") AS FolderFullName  FROM " + BaseFileTable.TableName + " WHERE " + BaseFileTable.FieldID + " = " + base.DbHelper.GetParameter(BaseFileTable.FieldID);
            DataTable dataTable = new DataTable(BaseFileTable.TableName);
            base.DbHelper.Fill(dataTable, sqlQuery, base.DbHelper.MakeParameters(BaseFileTable.FieldID, id));
            return new BaseFileEntity(dataTable);
        }

        public int GetFileCount()
        {
            string sqlQuery = " SELECT COUNT(*) FROM ECP_File ";
            return int.Parse(base.DbHelper.ExecuteScalar(sqlQuery).ToString());
        }

        public int GetFileCount(bool enabled)
        {
            string sqlQuery = " SELECT COUNT(*) FROM ECP_File WHERE Enabled = ";
            sqlQuery = sqlQuery + (enabled ? "1" : "0");
            return int.Parse(base.DbHelper.ExecuteScalar(sqlQuery).ToString());
        }

        public int GetFileCount(string userID)
        {
            string sqlQuery = " SELECT COUNT(*) FROM ECP_File WHERE CreateUserID='" + userID + "'";
            return int.Parse(base.DbHelper.ExecuteScalar(sqlQuery).ToString());
        }

        public int GetFileCount(string folderID, string userID)
        {
            string sqlQuery = " SELECT SUM(FileSize * ReadCount) FROM ECP_File  WHERE CreateUserID='" + userID + "' AND " + BaseFolderTable.FieldParentID + " = '" + folderID + "'";
            return int.Parse(base.DbHelper.ExecuteScalar(sqlQuery).ToString());
        }

        public int GetFlowmeter()
        {
            string sqlQuery = "SELECT SUM(FileSize * ReadCount) FROM ECP_File ";
            return int.Parse(base.DbHelper.ExecuteScalar(sqlQuery).ToString());
        }

        public int GetFlowmeter(string userID)
        {
            string sqlQuery = "SELECT SUM(FileSize * ReadCount) FROM ECP_File  WHERE CreateUserID='" + userID + "'";
            return int.Parse(base.DbHelper.ExecuteScalar(sqlQuery).ToString());
        }

        public DataTable GetListByFolder(string id)
        {
            string sqlQuery = string.Empty;
            sqlQuery = " SELECT " + BaseFileTable.FieldID + "        ," + BaseFileTable.FieldFolderID + "        ," + BaseFileTable.FieldFileName + "        ," + BaseFileTable.FieldFilePath + "        ," + BaseFileTable.FieldFileSize + "        ," + BaseFileTable.FieldReadCount + "        ," + BaseFileTable.FieldCategory + "        ," + BaseFileTable.FieldDescription + "        ," + BaseFileTable.FieldEnabled + "        ," + BaseFileTable.FieldSortCode + "        ," + BaseFileTable.FieldCreateUserID + "        ," + BaseFileTable.FieldCreateUserRealname + "        ," + BaseFileTable.FieldCreateDate + "        ," + BaseFileTable.FieldModifyUserID + "        ," + BaseFileTable.FieldModifyUserRealname + "        ," + BaseFileTable.FieldModifyDate + "       , (SELECT " + BaseFolderTable.FieldFolderName + " FROM " + BaseFolderTable.TableName + " WHERE " + BaseFolderTable.FieldID + " = " + BaseFileTable.FieldFolderID + ") AS FolderFullName  FROM " + BaseFileTable.TableName + " WHERE " + BaseFileTable.FieldFolderID + " = " + base.DbHelper.GetParameter(BaseFileTable.FieldFolderID);
            DataTable dataTable = new DataTable(BaseFileTable.TableName);
            base.DbHelper.Fill(dataTable, sqlQuery, base.DbHelper.MakeParameters(BaseFileTable.FieldFolderID, id));
            if (id.Length == 0)
            {
                DataRow row = dataTable.NewRow();
                row[BaseFileTable.FieldEnabled] = 1;
                dataTable.Rows.Add(row);
                dataTable.AcceptChanges();
            }
            this.GetFrom(dataTable);
            return dataTable;
        }

        public double GetSumFileSize()
        {
            string sqlQuery = " SELECT SUM(FileSize) FROM ECP_File ";
            return double.Parse(base.DbHelper.ExecuteScalar(sqlQuery).ToString());
        }

        public double GetSumFileSize(bool enabled)
        {
            string sqlQuery = " SELECT SUM(FileSize) FROM ECP_File WHERE Enabled = ";
            sqlQuery = sqlQuery + (enabled ? "1" : "0");
            return double.Parse(base.DbHelper.ExecuteScalar(sqlQuery).ToString());
        }

        public double GetSumFileSize(string userID)
        {
            string sqlQuery = " SELECT SUM(FileSize) FROM ECP_File WHERE CreateUserID='" + userID + "'";
            return double.Parse(base.DbHelper.ExecuteScalar(sqlQuery).ToString());
        }

        public int MoveTo(string id, string folderID)
        {
            string property = this.GetProperty(id, BaseFileTable.FieldFileName);
            this.Delete(BaseFileTable.FieldFolderID, folderID, BaseFileTable.FieldFileName, property);
            return this.SetProperty(id, BaseFileTable.FieldFolderID, folderID);
        }

        public DataTable Search(string search)
        {
            string sqlQuery = string.Empty;
            sqlQuery = " SELECT " + BaseFileTable.FieldID + "        ," + BaseFileTable.FieldFolderID + "        ," + BaseFileTable.FieldFileName + "        ," + BaseFileTable.FieldFilePath + "        ," + BaseFileTable.FieldFileSize + "        ," + BaseFileTable.FieldReadCount + "        ," + BaseFileTable.FieldDescription + "        ," + BaseFileTable.FieldCategory + "        ," + BaseFileTable.FieldEnabled + "        ," + BaseFileTable.FieldSortCode + "        ," + BaseFileTable.FieldCreateUserID + "        ," + BaseFileTable.FieldCreateUserRealname + "        ," + BaseFileTable.FieldCreateDate + "        ," + BaseFileTable.FieldModifyUserID + "        ," + BaseFileTable.FieldModifyUserRealname + "        ," + BaseFileTable.FieldModifyDate + " FROM " + BaseFileTable.TableName + " WHERE " + BaseFileTable.FieldFileName + " LIKE " + base.DbHelper.GetParameter(BaseFileTable.FieldFileName) + " OR " + BaseFileTable.FieldDescription + " LIKE " + base.DbHelper.GetParameter(BaseFileTable.FieldDescription);
            DataTable dataTable = new DataTable(BaseFileTable.TableName);
            search = BaseBusinessLogic.GetSearchString(search);
            base.DbHelper.AttachAdapterParameters(base.DbHelper.MakeParameters(BaseFileTable.FieldFileName, search));
            base.DbHelper.AttachAdapterParameters(base.DbHelper.MakeParameters(BaseFileTable.FieldDescription, search));
            base.DbHelper.Fill(dataTable, sqlQuery);
            return dataTable;
        }

        public int Update(BaseFileEntity fileEntity, out string statusCode)
        {
            int num = 0;
            if (DbLogic.IsModifed(base.DbHelper, BaseFolderTable.TableName, fileEntity.ID, fileEntity.ModifyUserID, fileEntity.ModifyDate))
            {
                statusCode = StatusCode.ErrorChanged.ToString();
                return num;
            }
            if (this.Exists(BaseFileTable.FieldFolderID, fileEntity.FolderID, BaseFileTable.FieldFileName, fileEntity.FileName, fileEntity.ID))
            {
                statusCode = StatusCode.ErrorFullNameExist.ToString();
                return num;
            }
            num = this.UpdateEntity(fileEntity);
            if (num == 1)
            {
                statusCode = StatusCode.OKUpdate.ToString();
                return num;
            }
            statusCode = StatusCode.ErrorDeleted.ToString();
            return num;
        }

        public int Update(string id, string folderID, string fileName, string description, bool enabled, out string statusCode)
        {
            statusCode = string.Empty;
            SQLBuilder builder = new SQLBuilder(base.DbHelper);
            builder.BeginUpdate(BaseFileTable.TableName);
            builder.SetValue(BaseFileTable.FieldFolderID, folderID);
            builder.SetValue(BaseFileTable.FieldFileName, fileName);
            builder.SetValue(BaseFileTable.FieldEnabled, enabled);
            builder.SetValue(BaseFileTable.FieldDescription, description);
            builder.SetValue(BaseFileTable.FieldModifyUserID, base.UserInfo.ID);
            builder.SetValue(BaseFileTable.FieldModifyUserRealname, base.UserInfo.Realname);
            builder.SetDBNow(BaseFileTable.FieldModifyDate);
            builder.SetWhere(BaseFileTable.FieldID, id);
            int num = builder.EndUpdate();
            if (num > 0)
            {
                statusCode = StatusCode.OKUpdate.ToString();
                return num;
            }
            statusCode = StatusCode.ErrorDeleted.ToString();
            return num;
        }

        public int UpdateEntity(BaseFileEntity fileEntity)
        {
            SQLBuilder builder = new SQLBuilder(base.DbHelper);
            builder.BeginUpdate(BaseFileTable.TableName);
            builder.SetValue(BaseFileTable.FieldFileName, fileEntity.FileName);
            builder.SetValue(BaseFileTable.FieldFilePath, fileEntity.FilePath);
            builder.SetValue(BaseFileTable.FieldDescription, fileEntity.Description);
            builder.SetValue(BaseFileTable.FieldEnabled, fileEntity.Enabled ? 1 : 0);
            builder.SetValue(BaseFileTable.FieldSortCode, fileEntity.SortCode);
            builder.SetValue(BaseFileTable.FieldModifyUserID, base.UserInfo.ID);
            builder.SetValue(BaseFileTable.FieldModifyUserRealname, base.UserInfo.Realname);
            builder.SetDBNow(BaseFileTable.FieldModifyDate);
            builder.SetWhere(BaseFileTable.FieldID, fileEntity.ID);
            return builder.EndUpdate();
        }

        public int UpdateFile(string id, string fileName, byte[] file)
        {
            SQLBuilder builder = new SQLBuilder(base.DbHelper);
            builder.BeginUpdate(BaseFileTable.TableName);
            builder.SetValue(BaseFileTable.FieldFileName, fileName);
            if (file != null)
            {
                builder.SetValue(BaseFileTable.FieldFileContent, file);
                builder.SetValue(BaseFileTable.FieldFileSize, file.Length);
            }
            builder.SetValue(BaseFileTable.FieldModifyUserID, base.UserInfo.ID);
            builder.SetValue(BaseFileTable.FieldModifyUserRealname, base.UserInfo.Realname);
            builder.SetDBNow(BaseFileTable.FieldModifyDate);
            builder.SetWhere(BaseFileTable.FieldID, id);
            return builder.EndUpdate();
        }

        public int UpdateFile(string id, string fileName, byte[] file, out string statusCode)
        {
            statusCode = string.Empty;
            int num = this.UpdateFile(id, fileName, file);
            if (num > 0)
            {
                statusCode = StatusCode.OKUpdate.ToString();
                return num;
            }
            statusCode = StatusCode.ErrorDeleted.ToString();
            return num;
        }

        private int UpdateReadCount(string id)
        {
            SQLBuilder builder = new SQLBuilder(base.DbHelper);
            builder.BeginUpdate(BaseFileTable.TableName);
            builder.SetFormula(BaseFileTable.FieldReadCount, BaseFileTable.FieldReadCount + " + 1 ");
            builder.SetWhere(BaseFileTable.FieldID, id);
            return builder.EndUpdate();
        }

        public string Upload(string folderID, string fileName, byte[] file, bool enabled)
        {
            string str = this.FindID(BaseFileTable.FieldFolderID, folderID, BaseFileTable.FieldFileName, fileName);
            if (!string.IsNullOrEmpty(str))
            {
                this.UpdateFile(str, fileName, file);
                return str;
            }
            BaseFileEntity fileEntity = new BaseFileEntity
            {
                FolderID = folderID,
                FileName = fileName,
                FileContent = file,
                Enabled = enabled
            };
            return this.AddEntity(fileEntity);
        }
    }
}